<template>
  <div class="topic-management">
    <div class="head">
      <!-- 顶部工具栏 -->
      <el-form size="small" :inline="true">
        <el-form-item label="搜索">
          <el-input   @input="inputChange" v-model="searchInput" placeholder="输入题目编号或名称进行检索" class="search_input"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" plain icon="el-icon-plus" size="small" @click="openAddDialog">新增题目</el-button>
        </el-form-item>
        <el-form-item>
          <el-button :disabled="selectedTopics.length === 0" type="danger" plain icon="el-icon-delete" size="small" @click="deleteTopics">删除题目</el-button>
        </el-form-item>
      </el-form>
      <!--分页组件 v-show:是否显示，total：总数，page.sync：第几页，limit.sync：一页几个，pagination：触碰事件-->
      <pagination class="pagination"
                  v-show="total>0"
                  :total="total"
                  :page.sync="queryParams.pageNum"
                  :limit.sync="queryParams.pageSize"
                  @pagination="fetchTopics"/>
    </div>

    <div class="body">
      <!-- 题目列表 -->
      <el-table :data="topics" style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" ></el-table-column>
        <el-table-column prop="topicId" label="题目编号" sortable></el-table-column>
        <el-table-column prop="topicName" label="题目名称"></el-table-column>
        <el-table-column label="操作">
          <template v-slot:default="scope">
            <el-button size="mini" type="primary" @click="openEditDialog(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" plain @click="deleteTopic(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 编辑或新增题目的对话框 -->
    <el-dialog :title="flag === 0 ? '新增题目' : '题目详情'" :visible.sync="dialogVisible">
      <el-form :model="currentTopic">

          <el-form-item label="题目编号" v-show="flag==1">
          <el-input v-model="currentTopic.topicId" :disabled="true"></el-input>
          </el-form-item>

        <el-form-item label="题目名称">
          <el-input v-model="currentTopic.topicName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="题目备注">
          <el-input v-model="currentTopic.describe" autocomplete="off" type="textarea" :autosize="{ minRows: 2, maxRows: 4}"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button  @click="dialogVisible = false">取消</el-button>
        <el-button v-show="flag==0" type="primary" @click="addTopic">新增</el-button>
        <el-button v-show="flag==1" type="primary" @click="updateTopic">保存</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  addTopic,
  getTopicList,
  deleteTopic,
  updateTopic,
  getTopic
} from '@/api/system/topic';

export default {
  data() {
    return {
      searchInput: '',
      topics: [],
      selectedTopics: [],
      dialogVisible: false,
      currentTopic: { topicId: '', topicName: '' ,describe:'' },
      flag:0, //flag为0是为新增题目，为1时为编辑题目
      total:0,//题目总数
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
    };
  },
  computed: {
    // filteredTopics() {
    //   return this.topics.filter(topic => topic.topicName.includes(this.searchInput));
    // }
  },
  created() {
  },
  mounted(){
    this.fetchTopics();
  },
  methods: {
    handleSelectionChange(selection){
      //console.log("选中的题目",selection);
      this.selectedTopics = selection.map(item => item.topicId);
      //console.log("选中的题目id",this.selectedTopics);
    },
  inputChange(){
    //console.log("输入框值改变", this.searchInput);
    if (this.searchInput.trim() !== "") {  // 检查输入是否为空,使用trim()方法去除空格
      getTopic(this.searchInput).then(res => {
        //.log("获取id对应数据", res);
        if (res.code === 200) {
          this.topics = [];
          this.topics.push({
            topicId: res.data.topicId,
            topicName: res.data.topicName,
            describe: res.data.describe
          });
        }
      });
    }
    else{
      this.fetchTopics();
    }
  },
    fetchTopics() {
      this.topics=[];
      getTopicList(this.queryParams).then(res => {
        this.total=res.total;
        res.rows.forEach(item=>{
          this.topics.push({
            topicId:item.topicId,
            topicName:item.topicName,
            describe:item.describe
          })
        })
      }).catch(error => {
        console.error("Error fetching topics:", error);
      });
    },
    openAddDialog() {
      this.flag=0;
      this.currentTopic = { topicId: '', topicName: '' };
      this.dialogVisible = true;
    },
    openEditDialog(topic) {
      this.flag=1;
      this.currentTopic = { ...topic };
      this.dialogVisible = true;
    },
    addTopic(){
      let data={
        topicName:this.currentTopic.topicName,
        describe:this.currentTopic.describe,
        //lessonId:"11",   //lessonId不应该携带，后续删除
        //topicId:this.currentTopic.topicId,  //不需要传入
      }
      addTopic(data).then(res=>{
        //console.log(res);
        this.fetchTopics();
        this.dialogVisible = false;
      })
    },
    updateTopic() {
      let data={
        topicName:this.currentTopic.topicName,
        topicId:this.currentTopic.topicId,
        describe:this.currentTopic.describe,
      }
      updateTopic(data).then((res) => {
        //console.log(res)
        this.dialogVisible = false;
        this.fetchTopics();
      }).catch(error => {
        //console.error("Failed to save topic:", error);
      });
    },
    deleteTopics() {
      this.selectedTopics.forEach(topicId => {
        deleteTopic(topicId).then(() => {

        });
      });
      this.fetchTopics();
      this.selectedTopics = [];
    },
    deleteTopic(topic) {
      deleteTopic(topic.topicId).then(() => {
        this.fetchTopics();
      });
    }
  }
};
</script>
<style scoped>
.head{
  position: relative;
}
.topic-management {
  padding: 20px;
}
.search_input{
  width:200px
}
.pagination{
  position: absolute;
  top:-50%;
  right: 0;
}
</style>
